package com.springcloudalibaba.apiAsyn.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lkx.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @描述 https://www.likaixuan.top/excelUtil/doc/v3
 * @作者 lixing_java@163.com
 * @日期 2022/4/19
 */
@Controller
@RequestMapping("excel")
@Slf4j
public class ExcelController {

    /**
     * http://127.0.0.1:9999/excel/importExcel
     */
    @RequestMapping("importExcel")
    @ResponseBody
    public Object importExcel(MultipartFile[] files) {
        List<DemoVo> list = new ArrayList<>();
        Arrays.stream(files).forEach(file -> {
            try {
                list.addAll(ExcelUtil.readXls(file.getBytes(), DemoVo.class));
                log.info(JSON.toJSONString(list, SerializerFeature.WriteDateUseDateFormat));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return JSON.toJSONString(list, SerializerFeature.WriteDateUseDateFormat);
    }

    /**
     * http://127.0.0.1:9999/excel/exportExcel
     */
    @GetMapping("exportExcel")
    public void exportExcel(HttpServletResponse response) {
        DemoVo demoVo = new DemoVo();
        demoVo.setId(1516046450972233700L);
        demoVo.setName("测试");
        demoVo.setAge(28);
        demoVo.setScore(100.00);
        demoVo.setCreateTime(new Date());

        List<DemoVo> list = new ArrayList<>();
        list.add(demoVo);

        try {
            ExcelUtil.exportExcelOutputStream(response, list, DemoVo.class, "Excel导出");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * http://127.0.0.1:9999/excel/exportExcelByTemplate
     */
    @GetMapping("exportExcelByTemplate")
    public void exportExcelByTemplate(HttpServletResponse response) {
        DemoVo demoVo = new DemoVo();
        demoVo.setId(1516046450972233700L);
        demoVo.setName("测试1");
        demoVo.setAge(28);
        demoVo.setScore(100.00);
        demoVo.setCreateTime(new Date());
        try {
            ExcelUtil.templateWrite(response, "C:\\Users\\123\\Desktop\\Excel导出模板.xls", demoVo, "Excel导出模板");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
